import { ref, computed } from 'vue'
import { getAllProduct, getAdProduct, getProductByCategory } from '../api/home.js'
export const useHomeStore = () => {
  // 分类数据
  const categories = [
    { name: '服装' },
    { name: '数码' },
    { name: '家电' }
  ]

  const selectedCategory = ref('服装')
  const swiperImages = ref([])
  const smallImages = ref([])
  const categoryImages = ref([])//得到的就是allproduct
 
  // 选择分类
  const selectCategory = (categoryName) => {
    selectedCategory.value = categoryName
  }

  // 获取数据
  const fetchImages = async () => {
    try {
      // const response = await fetch('/images.json')
      // const data = await response.json()
      //console.log(data)
      const response2=await getAllProduct()
      categoryImages.value=response2.data.data;
     const adresponse=await getAdProduct()
    //   取出adresponse.data.data中不为空不为null的图片

      swiperImages.value=adresponse.data.data
      console.log('swiper',swiperImages.value)


      //从categoryImages中随机取四个商品
      for (let i = 0; i < 4; i++) {
        const randomIndex = Math.floor(Math.random() * categoryImages.value.length)
        smallImages.value.push(categoryImages.value[randomIndex])
        //categoryImages.value.splice(randomIndex, 1)
      }


      console.log('smallImages',smallImages.value)
      
      //smallImages.value = data.recommendproducts || []
      
      console.log('categoryImages',categoryImages.value)

    } catch (error) {
      console.error('Error loading images:', error)
    }
  }

  // 计算属性，根据选中的分类过滤商品
  const filteredCategoryImages = computed(() => {
    return categoryImages.value.filter(image => image.categoryname === selectedCategory.value)
  })

  return {
    categories,
    selectedCategory,
    swiperImages,
    smallImages,
    categoryImages,
    selectCategory,
    fetchImages,
    filteredCategoryImages
  }
}